const jwt = require('jsonwebtoken')
const log4js = require('./log4j')

const CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001,
  USER_ACCOUNT_ERROR: 20001,
  USER_LOGIN_ERROR: 30001,
  BUSINESS_ERROR: 40001,
  AUTH_ERROR: 50001
}

module.exports = {
  pager({ pageNum = 1, pageSize = 10 }) {
    pageNum = pageNum * 1
    pageSize = pageSize * 1

    const skipIndex = (pageNum - 1) * pageSize

    return {
      page: {
        pageNum,
        pageSize
      },
      skipIndex
    }
  },
  success(data = '', msg = '', code = CODE.SUCCESS) {
    log4js.debug(data)
    return {
      code,
      data,
      msg
    }
  },
  fail(msg = '', code = CODE.BUSINESS_ERROR, data = '') {
    log4js.debug(msg)
    return {
      code,
      data,
      msg
    }
  },
  CODE,
  decoded(authorization) {
    if (authorization) {
      const token = authorization.split(' ')[1]
      return jwt.verify(token, 'aicherish')
    }
    return ''
  },
  getTreeMenu(rootList, id, list) {
    for (let i = 0; i < rootList.length; i++) {
      let item = rootList[i]
      if (String(item.parentId.slice().pop()) == String(id)) {
        list.push(item._doc)
      }
    }
    list.map((item) => {
      item.children = []
      this.getTreeMenu(rootList, item._id, item.children)

      if (item.children.length === 0) {
        delete item.children
      } else if (item.children[0].menuType === 2) {
        item.action = item.children
      }
    })

    return list
  }
}
